<template>
    <div class="layout-pd">
        <div class="container ">
            <div class="search-btns flex items-center justify-between">
                <div class="btns"></div>
                <div class="search flex-1 mx-4 flex_cen relate">
                    <div class="icon-name" @click="showStatusFn">
                        <el-icon>
                            <SuccessFilled />
                        </el-icon>
                        <div class="ml10">选择状态</div>
                    </div>
                    <div v-if="showStatus" class="satus-class">
                        <div class="title1" @click="title1Fn">询价订单(全选/清空)</div>
                        <div class="checkbox1">
                            <el-checkbox-group v-model="title1Val" @change="changeBox1">
                                <el-checkbox v-for="item in title1ValArr" :key="item.id" :label="item.id"
                                    :value="item.id">
                                    <span>{{ item.label }}</span>
                                </el-checkbox>
                            </el-checkbox-group>
                        </div>
                        <div class="title2" @click="title2Fn">成交订单(全选/清空)</div>
                        <div class="checkbox2">
                            <el-checkbox-group v-model="title2Val" @change="changeBox2">
                                <el-checkbox v-for="item in title2ValArr" :key="item.id" :label="item.id"
                                    :value="item.id">
                                    <span>{{ item.label }}</span>
                                </el-checkbox>
                            </el-checkbox-group>
                        </div>
                        <div class="flex_cen_end">
                            <el-button type="primary" @click="submitSelect">确认选择</el-button>
                        </div>
                    </div>
                    <el-input v-model="state.formData.title" placeholder="订单号" class="input-with-select">
                        <template #append>
                            <el-button :icon="Search" @click="getData" />
                        </template>
                    </el-input>
                </div>
                <div class="batch_export">
                    <el-input v-model="state.formData.username" placeholder="客户姓名" class="input-with-select">
                        <template #append>
                            <el-button :icon="Search" @click="getData" />
                        </template>
                    </el-input>
                </div>
                <div class="batch_export">
                    <el-input v-model="state.formData.phone" placeholder="手机号" class="input-with-select">
                        <template #append>
                            <el-button :icon="Search" @click="getData" />
                        </template>
                    </el-input>
                </div>
                <div class="batch_export">
                    <el-input v-model="state.formData.email" placeholder="邮箱" class="input-with-select">
                        <template #append>
                            <el-button :icon="Search" @click="getData" />
                        </template>
                    </el-input>
                </div>
                <div class="batch_export">
                    <el-date-picker v-model="state.formData.dateRange" type="datetimerange" start-placeholder="开始时间"
                        end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                        @change="handleDateChange" />
                </div>
            </div>
            <div class="table-class">
                <div class="tables">
                    <table class="order-table header-table">
                        <thead>
                            <tr>
                                <th class="wid140">
                                    <div class="flex">
                                        <div>订单号</div>
                                        <div class="icons">
                                            <el-icon @click="iconClick('order_no', 'asc1')">
                                                <CaretTop :color="sortType === 'asc1' ? '#FF8800' : '#DDDDDD'" />
                                            </el-icon>
                                            <el-icon @click="iconClick('order_no', 'desc1')">
                                                <CaretBottom :color="sortType === 'desc1' ? '#FF8800' : '#DDDDDD'" />
                                            </el-icon>
                                        </div>
                                    </div>
                                </th>
                                <th class="wid140">订单金额（收款）</th>
                                <th class="wid140">
                                    <div class="flex">
                                        <div>物流金额（收款）</div>
                                        <div class="icons">
                                            <el-icon @click="iconClick('total_price', 'asc2')">
                                                <CaretTop :color="sortType === 'asc2' ? '#FF8800' : '#DDDDDD'" />
                                            </el-icon>
                                            <el-icon @click="iconClick('total_price', 'desc2')">
                                                <CaretBottom :color="sortType === 'desc2' ? '#FF8800' : '#DDDDDD'" />
                                            </el-icon>
                                        </div>
                                    </div>
                                </th>
                                <th class="wid100">是否售后</th>
                                <th class="wid100">售后金额</th>
                                <th class="wid100">操作</th>
                            </tr>
                        </thead>
                    </table>
                    <div class="body-wrapper">
                        <table v-if="state.tableData.length" class="order-table body-table">
                            <tbody>
                                <template v-for="(item, index) in state.tableData" :key="index">
                                    <tr>
                                        <td class="wid140">
                                            <div class="pre-break">{{ item.order_no }}</div>
                                            <div class="pre-break mt5">
                                                <el-icon @click="showInfos(item)">
                                                    <CaretBottom v-if="item.isShow" />
                                                    <CaretRight v-else />
                                                </el-icon>
                                            </div>
                                        </td>
                                        <td class="wid140">{{ item.order_price }}</td>
                                        <td class="wid140">{{ item.logistics_cost }}</td>
                                        <td class="wid100">{{ afterObj[item.after_sales_service] }}</td>
                                        <td class="wid100">{{ item.after_sales_service_price }}</td>
                                        <td class="wid100">
                                            <el-button type="primary" v-if="auth(state.isHasBtn1)" size="small"
                                                @click="clickGoEdit({ type: 'order', data: item })">编辑</el-button>
                                        </td>
                                    </tr>
                                    <template v-if="item.isShow">
                                        <tr class="borders">
                                            <td colspan="6">
                                                <div class="more_box" v-for="(itom, indox) in item.items" :key="indox">
                                                    <!-- 模型图 -->
                                                    <img class="product-img" :src="itom.model_img" alt="模型图" />
                                                    <!-- 图片 + 基础信息 -->
                                                    <div class="section-left">
                                                        <div class="basic-info">
                                                            <div class="product-name">
                                                                <label>{{ itom.pname }}</label>
                                                                <label class="indox">#{{ indox + 1 }}</label>
                                                                <el-icon class="download-icon cursors"
                                                                    @click="downLoadFile(itom, indox)">
                                                                    <UploadFilled />
                                                                </el-icon>
                                                            </div>
                                                        </div>
                                                        <div class="specs">
                                                            <div>volume: {{ parseSpec(itom.specifications)?.volume }}
                                                            </div>
                                                            <div>vertices: {{ parseSpec(itom.specifications)?.vertices
                                                                }}</div>
                                                            <div>surface: {{ parseSpec(itom.specifications)?.surface }}
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <!-- 服务与价格 -->
                                                    <div class="section-center">
                                                        <div class="service-item">
                                                            <label>生产工艺：</label>
                                                            <span>{{ itom.service_name }}</span>
                                                        </div>
                                                        <div class="service-item">
                                                            <label>单价：</label>
                                                            <span>{{ itom.price }}</span>
                                                        </div>
                                                    </div>

                                                    <!-- 右侧：详情信息（分组） -->
                                                    <div class="section-right">
                                                        <!-- 材料与后处理 -->
                                                        <div class="detail-group">
                                                            <div><label>材料：</label> {{ itom.material_name }}</div>
                                                            <div><label>后处理：</label> {{ itom.tags }}</div>
                                                            <div><label>数量：</label> {{ itom.pcount }}</div>
                                                        </div>
                                                    </div>

                                                    <div class="section-cb">
                                                        <div class="detail-group">
                                                            <div><label>客户备注：</label> {{ itom.content }}</div>
                                                            <div>
                                                                <label>客户文件备注：</label>
                                                                <div v-for="(file, index) in itom.files" :key="index"
                                                                    class="file-item">
                                                                    <a :href="file.path" download>{{ file.name }}</a>
                                                                </div>
                                                            </div>
                                                        </div>

                                                        <!-- 备注与交期 -->
                                                        <div class="detail-group">
                                                            <div><label>生产交期：</label> {{ itom.production_lead_time }}
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <!-- 操作区 -->
                                                    <div class="action-section" v-if="auth(state.isHasBtn2)">
                                                        <el-button type="primary" size="mini"
                                                            @click="clickGoEdit({ type: 'item', data: itom })">
                                                            编辑
                                                        </el-button>
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                    </template>
                                </template>
                            </tbody>
                        </table>
                        <div v-else class="no-data">暂无数据</div>
                    </div>
                </div>
                <div class="pagination">
                    <el-pagination v-model:current-page="state.pageSizeObj.curPage"
                        v-model:page-size="state.pageSizeObj.pageSize" :page-sizes="[5, 10, 20, 30, 40]"
                        layout="total, sizes, prev, pager, next, jumper" :total="state.pageSizeObj.total"
                        @size-change="handleSizeChange" @current-change="handleCurChange" />
                </div>
            </div>
        </div>
        <AddDialog ref="addDialogRef" @updateList="getData" @updateItem="handleUpdateItem"></AddDialog>
    </div>
</template>

<script setup name="PrintingOrderIndex">
import { CaretRight, CaretBottom, CaretTop, UploadFilled, SuccessFilled, Search } from '@element-plus/icons-vue'
import { orderIndex } from '/@/api/startfab/index';
import { auth } from '/@/utils/authFunction';
import { reactive, ref, onMounted, defineAsyncComponent, nextTick } from 'vue';
import axios from 'axios';
import { Local, Session } from '/@/utils/storage';
const AddDialog = defineAsyncComponent(() => import('./addPrinting.vue'));
const addDialogRef = ref()
const state = reactive({
    isHasBtn1: 'admin:admin:purchaseEdit1',
    isHasBtn2: 'admin:admin:purchaseEdit2',
    isHasBtn3: 'admin:admin:purchaseEdit',
    formData: {
        title: '',
        username: '',
        phone: '',
        email: '',
        dateRange: []
    },
    pageSizeObj: {
        curPage: 1,
        pageSize: 10,
        total: 0
    },
    columnData: [],
    tableData: []
})
const showStatus = ref(false)
const title1Val = ref([])
const title2Val = ref([])
const title1ValArr = ref([
    { id: 0, label: '文件上传完成&配置已完成' },
    { id: 1, label: '地址已完善' },
    { id: 2, label: '下单成功，等待付款（待付款）' },
    { id: 4, label: '审核不通过' },
    { id: 8, label: '订单取消' },
])
const title2ValArr = ref([
    { id: 3, label: '付款已确认/内部审核中' },
    { id: 4, label: '审核不通过' },
    { id: 5, label: '审核通过/生产中' },
    { id: 6, label: '生产完成/供应商发货' },
    { id: 7, label: '订单签收/订单完成' },
    { id: 11, label: '生产直接发到客户' },
    { id: 12, label: '已到仓/待发货' },
    { id: 13, label: '质检完成/发货中' },
    { id: 14, label: '订单完成/售后中' },
    { id: 15, label: '售后完成/售后生产中' },
    { id: 16, label: '售后完成/已发货' }
])
const statusPayType = ref({
    0: '待付款',
    1: '微信',
    2: '支付宝',
    3: '对公转账',
    4: 'PayPal',
})
const title1Boo2 = ref(false);
const handleSizeChange = (val) => {
    state.pageSizeObj.pageSize = val
    getData()
}
const handleCurChange = (val) => {
    state.pageSizeObj.curPage = val
    getData()
}
const getData = () => {
    const sort = fieldType.value ? `${fieldType.value} ${lastSort.value}` : ''
    const arrAll = title1Val.value.concat(title2Val.value)
    const result = arrAll.filter(item => item !== 0 && item !== 1)
    const params = {
        page: state.pageSizeObj.curPage,
        pageNum: state.pageSizeObj.pageSize,
        search: state.formData.title,
        username: state.formData.username,
        phone: state.formData.phone,
        email: state.formData.email,
        start_time: state.formData.dateRange[0],
        end_time: state.formData.dateRange[1],
        sort: sort,
        current_step: title1Val.value.includes(0) ? '3' : '',
        addresses_id: title1Val.value.includes(1) ? '1' : '',
        order_status: result,
        service_id: 1
    }
    orderIndex(params).then((res) => {
        showStatus.value = false
        if (res.code === 10000) {
            state.tableData = res.data.list
            state.pageSizeObj.total = res.data.pageInfo.count
        }
    })
}
const afterObj = ref({ 1: '否', 2: '是' });
const sortType = ref('')
const fieldType = ref('')
const lastSort = ref('')
const sortTypeObj = ref({
    asc1: 'asc',
    desc1: 'desc',
    asc2: 'asc',
    desc2: 'desc',
    asc3: 'asc',
    desc3: 'desc',
    asc4: 'asc',
    desc4: 'desc'
})
const iconClick = (filed, type) => {
    sortType.value = type
    fieldType.value = filed
    lastSort.value = sortTypeObj.value[type]
    getData()
}
const showInfos = row => {
    row.isShow = !row.isShow
}
const downLoadFile = async (row, idx) => {
    const params = {
        item_id: row.id,
        number: idx + 1,
        signature: Local.get('signatureLocal') || ''
    }
    try {
        const urls = `${import.meta.env.VITE_API_URL}/admin/order/download`
        const obj = {
            responseType: 'blob',
            headers: {
                'x-access-token': Session.get('token'),
                'X-Access-Appid': 'admin'
            }
        }
        const response = await axios.post(urls, params, obj)
        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', row.new_resources_url)
        document.body.appendChild(link);
        link.click();
        link.remove();
    } catch (error) { /* empty */ }
}
const clickGoEdit = (payload) => {
    if (payload.type === 'order') {
        addDialogRef.value.openDialog('edit', payload.data, payload.type);
    } else if (payload.type === 'item') {
        addDialogRef.value.openDialog('edit', payload.data, payload.type);
    }
}
const showStatusFn = () => {
    if (!showStatus.value) {
        title1Val.value = []
        title2Val.value = []
    }
    showStatus.value = !showStatus.value
}
const title1Fn = () => {
    if (!title1Bool.value) {
        title1Val.value = title1ValArr.value.map(item => item.id)
    } else {
        title1Val.value = []
    }
    nextTick(() => { title1Bool.value = !title1Bool.value })
}
const changeBox1 = (val) => {
    title1Bool.value = val.length == title1ValArr.value.length ? true : false
}
const title2Fn = () => {
    if (!title1Boo2.value) {
        title2Val.value = title2ValArr.value.map(item => item.id)
    } else {
        title2Val.value = []
    }
    nextTick(() => { title1Boo2.value = !title1Boo2.value })
}
const changeBox2 = (val) => {
    title1Boo2.value = val.length == title2ValArr.value.length ? true : false
}
const submitSelect = () => {
    getData()
}
// 处理日期选择变化
const handleDateChange = (dateRange) => {
    if (dateRange && dateRange[0] && dateRange[1]) {
        if (new Date(dateRange[0]) > new Date(dateRange[1])) {
            ElMessage.error('开始时间不能晚于结束时间');
            state.formData.dateRange = [];
            return;
        }
        getData();
    } else {
        ElMessage.error('请选择完整的时间范围');
    }
};
const parseSpec = (specStr) => {
    if (!specStr) return {};
    try {
        return JSON.parse(specStr);
    } catch (e) {
        console.warn('Failed to parse specifications:', specStr);
        return {};
    }
};
const handleUpdateItem = (updatedData, type) => {
    if (type === 'order') {
        const index = state.tableData.findIndex(order => order.orderid === updatedData.orderid);
        if (index !== -1) {
            Object.assign(state.tableData[index], updatedData);
            console.log('订单更新成功:', state.tableData[index]);
        }
    } else if (type === 'item') {
        for (const order of state.tableData) {
            if (!Array.isArray(order.items)) continue;
            const itemIndex = order.items.findIndex(item => item.id === updatedData.id);
            if (itemIndex !== -1) {
                order.items[itemIndex] = updatedData;
                break;
            }
        }
    }
};
onMounted(() => {
    getData()
})
</script>

<style scoped lang="scss">
.tips-content {
    width: 4px;
    height: 4px;
    border-radius: 50%;
    position: absolute;
    right: -2px;
    top: -2px;
    background-color: #f00;
}

.flex_cen {
    display: flex;
    align-items: center;
}

.flex_cen_cen {
    display: flex;
    align-items: center;
    justify-content: center;
}

.mt5 {
    margin-top: 5px;
}

.mr5 {
    margin-right: 5px;
}

.mr50 {
    margin-right: 40px;

    .mr20 {
        margin-top: 10px;
    }

    .mr10 {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
}

.mr51 {
    display: flex;
    text-align: center;

    .mr51-div {
        line-height: 18px;
    }
}

.cursors {
    cursor: pointer;
}

.container {
    background: #FFFFFF;
    padding: 15px;

    ::v-deep .search-btns {
        display: flex;
        align-items: center;
        // justify-content: space-between;

        .el-input-group__append {
            padding: 0px 15px;

            .el-icon {
                color: #333333;
                margin-right: 0px;
            }
        }

        .el-button {
            color: #FFFFFF;
        }

        .batch_export {
            margin-left: 10px;
        }
    }

    .table-class {
        margin-top: 10px;
        background: #FFFFFF;

        .tables {
            width: 100%;
            overflow-x: auto;
        }

        .pagination {
            margin-top: 10px;
            display: flex;
            align-items: center;
            justify-content: flex-end;
        }

        tr th {
            border: 1px solid #eee !important;
            border-bottom: 0px !important;
            background: #f5fbff;
        }

        .header-table {}
    }

    .table-class {
        margin-top: 10px;
        background: #FFFFFF;

        .tables {
            width: 100%;
            overflow-x: auto;
        }

        .pagination {
            margin-top: 10px;
            display: flex;
            align-items: center;
            justify-content: flex-end;
        }

        tr th {
            border: 1px solid #eee !important;
            border-bottom: 0px !important;
            background: #f5fbff;
        }

        .header-table {
            position: relative;
            z-index: 2;
            background-color: white;
            table-layout: fixed;
        }

        .body-wrapper {
            border-top: none;
        }

        .body-table {
            width: 100%;
            table-layout: fixed;
            border-collapse: collapse;
        }

        .order-table {
            width: 100%;
            border-collapse: collapse;

            th,
            td {
                border: 1px solid #eee;
                padding: 4px;
                text-align: left;
                height: 50px;
            }

            td {
                font-size: 13px;
            }
        }

        .flex {
            display: flex;
            align-items: center;

            .icons {
                margin-left: 5px;
                display: flex;
                flex-direction: column;

                .el-icon {
                    height: 10px;
                    cursor: pointer;
                }
            }
        }

        .borders {
            border-left: 1px solid #cccccc;
            border-right: 1px solid #cccccc;
            padding: 10px;

            .more_box {
                width: 100%;
                background: #fff;
                margin: 12px 0;
                border-radius: 8px;
                border: 1px solid rgba(0, 194, 130, 0.2);
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
                padding: 16px;
                display: flex;
                flex-wrap: wrap;
                gap: 20px;
                font-size: 13px;
                align-items: flex-start;

                .product-img {
                    width: 70px;
                    height: 70px;
                    object-fit: contain;
                    margin-bottom: 10px;
                    border: 1px solid #eee;
                    border-radius: 4px;
                }

                // —————— 左侧：图片 + 基础信息 ——————

                .section-left {
                    flex: 1;
                    min-width: 180px;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    text-align: center;



                    .basic-info {
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        margin-bottom: 10px;

                        .product-name {
                            font-weight: 600;
                            margin-bottom: 4px;
                            max-width: 160px;
                            word-break: break-word;

                            .indox {
                                margin-left: 10px;
                            }

                            .download-icon {
                                color: #409eff;
                                font-size: 16px;
                                line-height: 18px;
                                margin-left: 6px;
                            }
                        }
                    }

                    .specs>div {
                        margin: 2px 0;
                        color: #666;
                        font-size: 12px;
                    }
                }

                // —————— 中部：服务与价格 ——————
                .section-center {
                    flex: 1;
                    min-width: 200px;
                    display: flex;
                    flex-direction: column;
                    gap: 10px;

                    .service-item {
                        display: flex;
                        align-items: flex-start;

                        label {
                            font-weight: 600;
                            color: #333;
                            min-width: 110px;
                            flex-shrink: 0;
                        }

                        span {
                            color: #555;
                            flex: 1;
                            word-break: break-word;
                        }
                    }
                }

                // —————— 右侧：基础详情 ——————
                .section-right {
                    flex: 1.5;
                    min-width: 240px;
                    display: flex;
                    flex-direction: column;
                    gap: 14px;

                    .detail-group {
                        display: flex;
                        flex-direction: column;
                        gap: 6px;

                        label {
                            font-weight: 600;
                            color: #333;
                            margin-bottom: 2px;
                        }

                        >div {
                            display: flex;
                            flex-wrap: wrap;
                            align-items: flex-start;
                            gap: 6px 12px;

                            label {
                                font-weight: normal;
                                color: #555;
                                min-width: 80px;
                                flex-shrink: 0;
                            }
                        }
                    }

                    .file-item {

                        a {
                            color: #409eff;
                            text-decoration: none;
                        }

                        a:hover {
                            text-decoration: underline;
                        }
                    }
                }

                .section-cb {
                    flex: 1.2;
                    min-width: 220px;
                    display: flex;
                    flex-direction: column;
                    gap: 14px;

                    .detail-group {
                        display: flex;
                        flex-direction: column;
                        gap: 6px;

                        label {
                            font-weight: 600;
                            color: #333;
                            margin-bottom: 2px;
                        }

                        >div {
                            display: flex;
                            flex-wrap: wrap;
                            align-items: flex-start;
                            gap: 6px 12px;

                            label {
                                font-weight: normal;
                                color: #555;
                                min-width: 110px;
                                flex-shrink: 0;
                            }
                        }
                    }

                    .logistics-group {
                        .logistics-img {
                            width: 80px;
                            height: 80px;
                            margin-top: 6px;
                            border-radius: 4px;
                            object-fit: cover;
                        }
                    }
                }

                // —————— 操作区 ——————
                .action-section {
                    align-self: flex-start;
                    margin-left: auto;
                    padding-top: 20px;
                    flex-shrink: 0;
                }
            }
        }
    }
}

.wid140 {
    width: 140px;
    padding: 5px 10px;
}

.wid80 {
    width: 80px;
    padding: 5px 10px;
}

.wid100 {
    width: 100px;
    padding: 5px 10px;
}

.img2 {
    width: 80px;
    height: 40px;
    object-fit: contain;
}

.wid101 {
    width: 140px;
}

.bgnum {
    width: fit-content;
    line-height: 20px;
    margin-right: 10px;
    background: #00c282;
    color: #fff;
    font-style: normal;
    border-radius: 3px;
    font-size: 12px;
    margin: 5px 0 0 0;
    padding: 0 5px;
}

.flex_cen {
    display: flex;
    align-items: center;
}

.icon-name {
    width: 140px;
    height: 40px;
    background: #f4f4f4;
    border-radius: 4px;
    cursor: pointer;
    margin-right: 10px;
    display: flex;
    align-items: center;
    justify-content: center;

    .ml10 {
        margin-left: 10px;
    }
}

.relate {
    position: relative;
}

.satus-class {
    position: absolute;
    z-index: 9;
    left: 0px;
    top: 40px;
    background: #fff;
    border-radius: 4px;
    padding: 10px 15px 15px;
    box-shadow: 0 0px 10px rgba(0, 0, 0, 0.05);
    border: 1px solid #ddd;
    width: 370px;

    .title1,
    .title2 {
        width: 100%;
        line-height: 30px;
        background: #eee;
        margin: 10px 0 6px;
        text-indent: 13px;
        border-left: 4px solid #00c282;
        cursor: pointer;
    }
}

.flex_cen_end {
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

.no-data {
    text-align: center;
}
</style>